package com.xzx.flink.streamapi.mutilstream;

import com.xzx.flink.bean.ClickEvent;
import com.xzx.flink.streamapi.source.ClickSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @version 1.0
 * @auther xinzhixuan
 * @date 2022/5/4 21:36
 */
public class UnionTest {
    private static final OutputTag<ClickEvent> maryTag = new OutputTag<ClickEvent>("mary-pv"){};
    private static final OutputTag<ClickEvent> bobTag = new OutputTag<ClickEvent>("bob-pv"){};

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<ClickEvent> processStream = env.addSource(new ClickSource())
                .process(new ProcessFunction<ClickEvent, ClickEvent>() {
                    @Override
                    public void processElement(ClickEvent value, ProcessFunction<ClickEvent, ClickEvent>.Context ctx, Collector<ClickEvent> out) throws Exception {
                        if (value.getUser().equals("Mary")) {
                            ctx.output(maryTag, value);
                        } else if (value.getUser().equals("Bob")) {
                            ctx.output(bobTag, value);
                        } else {
                            out.collect(value);
                        }
                    }
                });
        processStream.print("main");
        processStream.getSideOutput(maryTag).print("mary");
        processStream.getSideOutput(bobTag).print("bob");

        processStream.union(processStream.getSideOutput(maryTag), processStream.getSideOutput(bobTag)).print("all");

        env.execute(UnionTest.class.getSimpleName());
    }
}
